package com.tangding.service.role;

import java.util.List;

import javax.annotation.PostConstruct;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mongodb.client.model.Filters;
import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.DateUtils;
import com.tangding.service.dao.role.RoleRepository;
import com.tangding.service.dao.user.UserRepository;
import com.tangding.service.entity.role.Role;
import com.tangding.service.entity.user.User;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年11月9日_上午10:03:12
 *
 */
@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	RoleRepository roleRepository;
	
	@Autowired
	UserRepository userRepository;

	@Override
	public List<Role> getRoles(List<Integer> ids) throws GException {
		return roleRepository.findRolesByIds(ids);
	}

	@Override
	public List<Role> getRoles(String uid) throws GException {
		Document condition = new Document();
		condition.put("uid", uid);
		User user = userRepository.findOne(condition);
		if (user == null) {
			throw new GException(ErrorConstants.USER_NOT_FOUND);
		}
		
		return getRoles(user.getRoles());
	}

	@Override
	public void add(Role role) throws GException {
		int roleId = DateUtils.getNow();
		Document condition = new Document();
		condition.put("roleId", roleId);
		Role one = roleRepository.findOne(condition);
		int index = 5;
		while (one != null && index > 0) {
			roleId = DateUtils.getNow();
			condition.put("roleId", roleId);
			one = roleRepository.findOne(condition);
			index --;
		}
		
		if (one != null) {
			throw new GException(ErrorConstants.ERR_CREATE_ROLE);
		}
		
		role.setRoleId(roleId);
		roleRepository.save(role);
	}

	@Override
	public List<Role> list() throws GException {
		return roleRepository.findAll();
	}

	@Override
	public void delete(Integer... ids) throws GException {
		Bson condition = Filters.in("roleId", ids);
		roleRepository.delete(condition);
	}

	@Override
	public void update(Role role) throws GException {
		Document condition = new Document();
		int roleId = role.getRoleId();
		condition.put("roleId", roleId);
		Role one = roleRepository.findOne(condition);
		if (one == null) {
			throw new GException(ErrorConstants.ERR_NO_ROLE);
		}
		
		roleRepository.update(role, condition);
	}
}
